using Microsoft.AspNetCore.Mvc;
using Demo.Repository;
using Demo.Models;
using System.Linq;
using Demo.RequestParam;
using System.Collections.Generic;

namespace Demo.Controllers
{
    public class ProductController : Controller
    {
        public IActionResult Index()
        {
            var EfCategory=new EfRepository<Category>();
            var Category=EfCategory.Table.FirstOrDefault();
            if(Category==null){
                EfCategory.Insert(new Category{
                    CategoryName="我是默认品类"
                });
            }
            var EFProduct = new EfRepository<Product>();
            var Product = EFProduct.Table.Where(x => x.IsDeleted == false).ToList();
            return View(Product);
        }
        public IActionResult CreateOrEdit(int id)
        {
            var EFProduct = new EfRepository<Product>();
            var Product = EFProduct.Table.Where(x => x.Id == id).FirstOrDefault();
            return View(Product);
        }
        [HttpPost]
        public IActionResult Save(ProductRequest model)
        {
            var EFProduct = new EfRepository<Product>();
            if (model.Id > 0)
            {
                var Product = EFProduct.GetById(model.Id);
                if (Product != null)
                {
                    Product.ProductName = model.ProductName;
                    Product.Supplier = model.Supplier;
                    Product.Price = model.Price;
                    Product.Stock = model.Stock;
                    Product.Remarks = model.Remarks;
                    EFProduct.Update(Product);
                }
            }
            else
            {
                EFProduct.Insert(
                new Product
                {
                    ProductName = model.ProductName,
                    Supplier = model.Supplier,
                    Price = model.Price,
                    Stock = model.Stock,
                    Remarks = model.Remarks,
                    CategoryNameid=1
                });
            }
            return Ok();
        }

        public IActionResult Query(ProductQueryRequest request)
        {
            var EFProduct = new EfRepository<Product>();
            List<Product> Product;
            if (request != null && request.Keyword != null && request.Keyword.Length > 0)
            {
                Product = EFProduct.Table
                            .Where(x => x.IsDeleted == false && (x.ProductName.Contains(request.Keyword)))
                            .ToList();
            }
            else
            {
                Product = EFProduct.Table
            .Where(x => x.IsDeleted == false)
            .ToList();
            }
            return Json(Product);
        }

        public IActionResult Delete(int id)
        {
            var Rep = new EfRepository<Product>();
            Rep.Delete(id);
            return RedirectToAction("Index");
        }

    }
}